<!-- Worker Statistics -->
<h3>Your Stats & Payment History</h3>

<div id="workerStats" class="stats">
    <div class="input-group">
        <input class="form-control" id="yourStatsInput" type="text" placeholder="Enter Your Address">
        <span class="input-group-btn"><button class="btn btn-default" type="button" id="lookUp">
            <span><i class="fa fa-search"></i> Lookup</span>
            <span><i class="fa fa-refresh fa-spin"></i> Searching...</span>
        </button></span>
    </div>
    <div id="addressError"></div>

    <!-- Statistics -->
    <div class="row yourStats">
        <div class="col-xs-12"><h4>Hash Rate</h4></div>
        <div class="col-lg-4 col-sm-6 stats">
            <div><i class="fa fa-tachometer"></i> Current Hash Rate: <span id="yourHashrateHolder"></span></div>
            <div><i class="fa fa-clock-o"></i> Last Share Submitted: <span id="yourLastShare"></span></div>
            <div><i class="fa fa-cloud-upload"></i> Total Hashes Submitted: <span id="yourHashes"></span></div>
        </div>
        <div class="col-lg-8 col-sm-6">
            <div class="userChart" data-chart="user_hashrate">
                <div class="chart">
                    
                </div>                
            </div>
        </div> 
	<br/>
	
        <div class="col-xs-12"><h4>Payments</h4></div>
        <div class="col-lg-4 col-sm-6 stats">
            <div><i class="fa fa-bank"></i> Pending Balance: <span id="yourPendingBalance"></span></div>
            <div><i class="fa fa-money"></i> Total Paid: <span id="yourPaid"></span></div>
            <div><i class="fa fa-money"></i> Current Payout Estimate: <span id="yourPayoutEstimate"></span></div>
        </div>
        <div class="col-lg-8 col-sm-6">
            <div class="userChart" data-chart="user_payments">
                <div class="chart">
                    
                </div> 
            </div>
        </div>       
    </div>

    <!-- Workers -->
    <h4 class="yourWorkers">Workers Statistics</h4>
    <div id="workersReport" class="yourWorkers table-responsive">
        <table class="table table-hover table-striped">
            <thead>
            <tr>
                <th class="col1 sort">Status <i class="fa fa-sort"></i></th>
                <th class="col2 sort">Worker Name <i class="fa fa-sort"></i></th>
                <th class="col3 sort">Hash Rate <i class="fa fa-sort"></i></th>
                <th class="col4 sort">Last Share Submitted <i class="fa fa-sort"></i></th>
                <th class="col5 sort">Total Hashes Submitted <i class="fa fa-sort"></i></th>
            </tr>
            </thead>
            <tbody id="workersReport_rows">

            </tbody>
        </table>
    </div>
    
    <!-- Payments -->
    <h4 class="yourStats">Payments History</h4>
    <div id="workerPayments" class="yourStats table-responsive">
        <table class="table table-hover table-striped">
            <thead>
            <tr>
                <th class="col1">Time Sent</th>
                <th class="col2">Transaction Hash</th>
                <th class="col3">Amount</th>
                <th class="col4">Mixin</th>
            </tr>
            </thead>
            <tbody id="paymentsReport_rows">

            </tbody>
        </table>
    </div>
    <p class="yourStats text-center">
        <button type="button" class="btn btn-default" id="loadMorePayments">Load More</button>
    </p>

</div>

<!-- Javascript -->
<script>
currentPage = {
    destroy: function(){
        $('#yourLastShare').timeago('dispose');
        if (xhrAddressPoll) xhrAddressPoll.abort();
        if (addressTimeout) clearTimeout(addressTimeout);
        if (xhrGetPayments) xhrGetPayments.abort();
    },
    update: function(){
    }
};

$('#yourLastShare').timeago();


var xhrAddressPoll;
var addressTimeout;

function fetchAddressStats(longpoll){
    var address = getCurrentAddress();
    
    xhrAddressPoll = $.ajax({
        url: api + '/stats_address',
        data: {
            address: address,
            longpoll: longpoll
        },
        dataType: 'json',
        cache: 'false',
        success: function(data){                    
            if (!data.stats){
                $('.yourStats, .yourWorkers, .userChart').hide();
                $('#addressError').text(data.error).show();
                docCookies.setItem('mining_address', '', Infinity);
                loadLiveStats(true);
                return;
            }

            $('#addressError').hide();

            if (data.stats.lastShare) {
                $('#yourLastShare').timeago('update', new Date(parseInt(data.stats.lastShare) * 1000).toISOString());
            }
            else {
                updateText('yourLastShare', 'Never');
            }

            updateText('yourHashrateHolder', (getReadableHashRateString(data.stats.hashrate) || '0 H') + '/sec');
            updateText('yourHashes', (data.stats.hashes || 0).toString());
            updateText('yourPaid', getReadableCoins(data.stats.paid));
            updateText('yourPendingBalance', getReadableCoins(data.stats.balance));

            var userRoundHashes = parseInt(data.stats.roundHashes || 0);
	    var poolRoundHashes = parseInt(lastStats.pool.roundHashes || 0);
	    var lastReward = parseFloat(lastStats.network.reward || 0);
	    
            var poolFee = lastStats.config.fee;
            if (Object.keys(lastStats.config.donation).length) {
                var totalDonation = 0;
                for(var i in lastStats.config.donation) {
                    totalDonation += lastStats.config.donation[i];
                }
                poolFee += totalDonation;
            }
	    var transferFee = lastStats.config.transferFee;
	    
            var payoutEstimatePct = parseFloat(userRoundHashes * 100 / poolRoundHashes)
	    var payoutEstimate = Math.round(lastReward * (payoutEstimatePct / 100));
            if (poolFee) payoutEstimate = payoutEstimate - (payoutEstimate * poolFee);
            if (transferFee) payoutEstimate = payoutEstimate - transferFee;
	    if (payoutEstimate < 0) payoutEstimate = 0;
	    updateText('yourPayoutEstimate', getReadableCoins(payoutEstimate, 4));
	    
            renderPayments(data.payments);
	    
            if (data.workers && data.workers.length > 0) {
                renderWorkers(data.workers);
                $('.yourWorkers').show();
            }
	    
            $('.yourStats').show();
            createUserCharts(data);                                
	    
            fetchAddressStats(true);
        },
        error: function(e){
            if (e.statusText === 'abort') return;
            $('#addressError').text('Connection error').show();
        
            if (addressTimeout) clearTimeout(addressTimeout);
            addressTimeout = setTimeout(function(){
                fetchAddressStats(false);
            }, 2000);
        }
    });
}
    
$('#lookUp').click(function(){
    var address = $('#yourStatsInput').val().trim();
    
    if (getCurrentAddress() != address) {
        docCookies.setItem('mining_address', address, Infinity);
    
        var urlWalletAddress = location.search.split('wallet=')[1] || 0;
        if (urlWalletAddress){
            window.location.href = "/#worker_stats";
            return ;
        }
        else {
            docCookies.setItem('mining_address', address, Infinity);
            loadLiveStats(true);
        }
    }

    $('#addressError, .yourStats, .yourWorkers, .userChart').hide();
    $('#workersReport_rows').empty();
    $('#paymentsReport_rows').empty();

    $('#lookUp > span:first-child').hide();
    $('#lookUp > span:last-child').show();

    if (xhrAddressPoll) xhrAddressPoll.abort();
    if (addressTimeout) clearTimeout(addressTimeout);

    $('#lookUp > span:last-child').hide();
    $('#lookUp > span:first-child').show();
    
    if (!address){
        $('#yourStatsInput').focus();
        return;
    }
    
    fetchAddressStats(false);
});
    
var workerCharts = {
    hashrate: {
        type: 'line',
        width: '100%',
        height: '120',
        lineColor: '#03a9f4',
        fillColor: 'rgba(3, 169, 244, .4)',
        spotColor: null,
        minSpotColor: null,
        maxSpotColor: null,
        highlightLineColor: '#236d26',
        spotRadius: 3,
        drawNormalOnTop: false,
        chartRangeMin: 0,
        tooltipFormat: '<b>{{y}}</b> &ndash; {{offset:names}}'
    },
    payments: {
        type: 'line',
        width: '100%',
        height: '120',
        lineColor: '#03a9f4',
        fillColor: 'rgba(3, 169, 244, .3)',
        spotColor: null,
        minSpotColor: null,
        maxSpotColor: null,
        highlightLineColor: '#236d26',
        spotRadius: 3,
        drawNormalOnTop: false,
        chartRangeMin: 0,
        tooltipFormat: '<b>{{y}}</b> &ndash; {{offset:names}}'
    }
};

$(function() {
    $('[data-toggle="tooltip"]').tooltip();
});

$('#workersReport th.sort').on('click', sortTable);
    
function createUserCharts(data) {
    for(var chart in workerCharts) {
        if(data['charts'][chart] && data['charts'][chart].length) {
            var graphData = getGraphData(data['charts'][chart], chart == 'payments');
            workerCharts[chart].tooltipValueLookups = {names: graphData.names};
            $('[data-chart=user_' + chart + ']').show().find('.chart').sparkline(graphData.values, workerCharts[chart]);
        }
    }
}

function getGraphData (rawData, fixValueToCoins) {
    var graphData = {
        names: [],
        values: []
    };
    
    if(rawData) {
        for (var i = 0, xy; xy = rawData[i]; i++) {
            graphData.names.push(new Date(xy[0]*1000).toLocaleString());
            graphData.values.push(fixValueToCoins ? getReadableCoins(xy[1], 4, true) : xy[1]);
        }
    }
    
    return graphData;
}

function getWorkerRowId(workerName){
    var id = btoa(workerName);
    id = id.replace(/=/, '');
    return id;
}

function getWorkerRowElement(worker, jsonString){
    var row = document.createElement('tr');
    row.setAttribute('data-json', jsonString);
    row.setAttribute('data-name', worker.name);
    row.setAttribute('id', 'workerRow_' + getWorkerRowId(worker.name));

    row.innerHTML = getWorkerCells(worker);

    return row;
}

function getWorkerCells(worker){
    var hashrate = worker.hashrate ? worker.hashrate : 0;
    var lastShare = worker.lastShare ? worker.lastShare : 0;
    var hashes = (worker.hashes || 0).toString();
    var status = (hashrate <= 0) ? 'error' : 'ok';
    
    return '<td class="col1" data-sort="' + status + '"><i class="fa fa-' + (status == 'ok' ? 'check status-ok' : 'times status-error') + '"></i></td>' +
           '<td class="col2" data-sort="' + (worker.name != 'undefined' ? worker.name : '') + '">' + (worker.name != 'undefined' ? worker.name : '<em>Undefined</em>') + '</td>' +
           '<td class="col3" data-sort="' + hashrate + '">' + getReadableHashRateString(hashrate) + '/sec</td>' +
           '<td class="col4" data-sort="' + lastShare + '">' + (lastShare ? $.timeago(new Date(parseInt(lastShare) * 1000).toISOString()) : 'Never') + '</td>' +
           '<td class="col5" data-sort="' + hashes + '">' + hashes + '</td>';
}

function sortWorkers(a, b){
  var aName = a.name.toLowerCase();
  var bName = b.name.toLowerCase(); 
  return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
}
      
function renderWorkers(workersData){
    workersData = workersData.sort(sortWorkers);
    
    var $workersRows = $('#workersReport_rows');
    
    for (var i = 0; i < workersData.length; i++){
        var existingRow = document.getElementById('workerRow_' + getWorkerRowId(workersData[i].name));
        if (!existingRow){
            $workersRows.empty();
            break;
        }
    }
    
    for (var i = 0; i < workersData.length; i++){
        var worker = workersData[i];
        var workerJson = JSON.stringify(worker);
        var existingRow = document.getElementById('workerRow_' + getWorkerRowId(worker.name));    
        if (existingRow && existingRow.getAttribute('data-json') !== workerJson){
            $(existingRow).replaceWith(getWorkerRowElement(worker, workerJson));
        }
        else if (!existingRow){
            var workerElement = getWorkerRowElement(worker, workerJson);
            $workersRows.append(workerElement);
        }
    }
}

function getPaymentCells(payment){
    return '<td class="col1">' + formatDate(payment.time) + '</td>' +
           '<td class="col2">' + formatPaymentLink(payment.hash) + '</td>' +
           '<td class="col3">' + getReadableCoins(payment.amount, 4, false) + '</td>' +
           '<td class="col4">' + payment.mixin + '</td>';
}

var xhrGetPayments;
$('#loadMorePayments').click(function(){
    if (xhrGetPayments) xhrGetPayments.abort();
    xhrGetPayments = $.ajax({
        url: api + '/get_payments',
        data: {
            time: $('#paymentsReport_rows').children().last().data('time'),
            address: address
        },
        dataType: 'json',
        cache: 'false',
        success: function(data){
            renderPayments(data);
        }
    });
});

var address = getCurrentAddress();
if (address){
    $('#yourStatsInput').val(address);
    $('#lookUp').click();
}

$('#yourStatsInput').keyup(function(e){
    if(e.keyCode === 13)
        $('#lookUp').click();
});
</script>
